const crypto = require('crypto');
const { format } = require('date-fns');
const WebSocket = require('ws');

class WsParam {
  constructor(APIKey, APISecret, gptUrl) {
    this.APIKey = APIKey;
    this.APISecret = APISecret;
    const url = new URL(gptUrl);
    this.host = url.host;
    this.path = url.pathname;
    this.gptUrl = gptUrl;
  }

  createUrl() {
    // 生成当前时间戳，符合 RFC1123 格式
    const date = format(new Date(), 'EEE, dd MMM yyyy HH:mm:ss OOOO');

    // 拼接字符串
    const signatureOrigin = `host: ${this.host}\n` +
                            `date: ${date}\n` +
                            `GET ${this.path} HTTP/1.1`;

    // 使用 HMAC-SHA256 对字符串进行签名
    const signatureSha = crypto.createHmac('sha256', this.APISecret)
      .update(signatureOrigin)
      .digest('base64');

    const authorizationOrigin = `api_key="${this.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signatureSha}"`;

    const authorization = Buffer.from(authorizationOrigin).toString('base64');

    // 将请求的鉴权参数组合为字典
    const v = {
      authorization,
      date,
      host: this.host
    };

    // 拼接鉴权参数，生成 URL
    const url = `${this.gptUrl}?${new URLSearchParams(v).toString()}`;
    return url;
  }
}

module.exports = WsParam;